#coding=utf-8

import os
import time
from SqliteTool import SqliteTool
from HttpTool import httpTool
from HttpTool import DownloadDisplay
from ExcelTool import ExcelTool
import threading

#下载镜像线程池
class DownloadThreadPool:
	def __init__(self,threadNum):
		self.threadInitNum = threadNum
		self.threadNum = threadNum
		self.downloadingList = list()
		self.progressList = list()
		self.mutex = threading.Lock()
	
	def UpdateThreadNum(self,type):
		self.mutex.acquire(1)
		if type:
			if self.threadNum < self.threadInitNum:
				self.threadNum += 1
		else:
			if self.threadNum > 0:
				self.threadNum -= 1
		self.mutex.release()

	def UpdateDownloadingList(self,type,downloadLink):
		self.mutex.acquire(1)
		if type:
			self.downloadingList.append(downloadLink)
		else:
			self.downloadingList.remove(downloadLink)
		self.mutex.release()

	def UpdateProgressList(self,type,downloadDisplay):
		self.mutex.acquire(1)
		if type:
			self.progressList.append(downloadDisplay)
		else
			self.progressList.remove(downloadDisplay)
		self.mutex.release()

	#显示进度条
	def UpdateProgress(self):
		if not self.progressList:
			return
		os.system('cls')
		for info in self.progressList:
			print("\r当前下载路径:" + info.downloadPath)
			print("\r当前下载镜像:" + info.isoName)
			print("\r" + str(info.value) + '% complete\n')

	def Download(self,ISOInfo,downloadDisplay):
		try:
			dirName = os.getcwd()+"\\ISODownload\\"+ISOInfo[2] +"\\"
			if not os.path.exists(dirName):
				os.mkdir(dirName)
			#创建进度显示信息对象
			downloadDisplay = DownloadDisplay()
			self.UpdateProgressList(True,downloadDisplay)
 			#存入正在下载镜像链表
			downloadLink = ISOInfo[5]
			self.UpdateDownloadingList(True,downloadLink)
			#创建日志对象
			excelTool = ExcelTool()
			excelTool.SetPageLink(ISOInfo[2])
			excelTool.SetISOName(ISOInfo[3])
			excelTool.SetISOSize(ISOInfo[6])
			excelTool.SetUpdateTime(ISOInfo[7])		
			#下载
			httpTool.DownLoad(downloadLink,dirName,downloadDisplay,excelTool)
			sqliteTool = SqliteTool()
			sqliteTool.SaveDownloadedISO(downloadLink)#存为已下载过镜像
			#从正在下载镜像链表中去除，从进度显示链表中去除，增加可用线程数
			self.UpdateThreadNum(True)
			self.UpdateDownloadingList(False,downloadLink)
			self.UpdateProgressList(False,downloadDisplay)
			#记录下载镜像信息
			excelTool.LogISOInfo()
		except:
			#从正在下载镜像链表中去除，从进度显示链表中去除，增加可用线程数
			self.UpdateThreadNum(True)
			self.UpdateDownloadingList(False,downloadLink)		
			self.UpdateProgressList(False,downloadDisplay)

	def Run(self):
		sqliteTool = SqliteTool()
		while True:
			self.UpdateProgress()
			#剩余线程数量为空，等待
			if self.threadNum<=0:
				time.sleep(1)
				continue
			ISOInfo = sqliteTool.FetchNextISOInfo(self.downloadingList)
			#如果已没有待下载镜像
			if not ISOInfo:
				if downloadingList:#如果还有镜像在下载，继续等待
					time.sleep(1)
					continue
				else:#全部下载完毕,返回
					return	
				
			#启动线程
			self.UpdateThreadNum(False)
			thread = threading.Thread(target = self.Download, args = (ISOInfo,downloadDisplay))	
			thread.start()	

#主函数
if not os.path.exists(os.getcwd()+"\\ISODownload\\"):
	os.mkdir(os.getcwd()+"\\ISODownload\\")
sqliteTool = SqliteTool()
#多线程
ThreadNum = 3#设定线程数量
downloadThreadPool = DownloadThreadPool(ThreadNum)
downloadThreadPool.Run()
os.system('cls')
print("全部镜像下载完成")

'''
#单线程
while True:
	#先下载未下载完镜像
	ISOInfo = sqliteTool.FetchNextDownloadingISOInfo()
	if ISOInfo:
		dirName = os.getcwd()+"\\ISODownload\\"+ISOInfo[1] +"\\"
		if not os.path.exists(dirName):
			os.mkdir(dirName)
		httpTool.DownLoad(ISOInfo[2],dirName)
		sqliteTool.SaveDownloadedISO(ISOInfo[2])#存为已下载过镜像
	#再下载抓取到的新镜像
	ISOInfo = sqliteTool.FetchNextISOInfo()
	if not ISOInfo:
		break
	dirName = os.getcwd()+"\\ISODownload\\"+ISOInfo[2] +"\\"
	if not os.path.exists(dirName):
		os.mkdir(dirName)
	sqliteTool.SaveDownloadingISO(ISOInfo[2],ISOInfo[5])
	httpTool.DownLoad(ISOInfo[5],dirName)
	sqliteTool.SaveDownloadedISO(ISOInfo[5])#存为已下载过镜像
	#ISOInfo = sqliteTool.FetchNextISOInfo()
print("全部镜像下载完成")
'''
